﻿package Cain.bgm
{
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.media.Sound;
	import flash.media.SoundChannel;
	import flash.media.SoundTransform;
	import flash.net.URLRequest;
	import gs.TweenLite;
	/**
	 * 音樂
	 * @author Cain
	 */
	public class Bgm extends EventDispatcher
	{
		private var bgm:Sound;
		private var bgmChl:SoundChannel;
		private var loop:Boolean;
		private var link:URLRequest;
		/**
		 * 撥完一次回傳 Event.SOUND_COMPLETE
		 */
		public function Bgm() 
		{
			setup();
		}
		
		private function setup():void
		{
			
		}
		public function load(_url:String):void 
		{
			link = new URLRequest(_url);
			bgm = new Sound(link);
		}
		public function play(_loop:Boolean = true):void 
		{
			loop = _loop;
			if (bgmChl == null) 
			{
				bgmChl = bgm.play();
				bgmChl.addEventListener(Event.SOUND_COMPLETE, bgmChl_onSOUND_COMPLETE);	
			}
			
		}
		
		private function bgmChl_onSOUND_COMPLETE(e:Event):void 
		{
			dispatchEvent(e);
			if (loop) 
			{
				bgm.play();
			}else 
			{
				bgmChl = null;
			}
			
		}
		public function sound_in(_t:Number = 1):void 
		{
			if (bgmChl!=null) 
			{
				TweenLite.to(bgmChl, _t, {volume:1});
			}
			
		}
		public function sound_out(_t:Number = 1):void 
		{
			if (bgmChl!=null) 
			{
				TweenLite.to(bgmChl, _t, { volume:0 } );
			}
		}
	}
	
}